<?php

function hexID($id, $ID = 900000000) {
    $id_encode = dechex($ID + $id);
    return strtoupper($id_encode);
}

function decID($id, $ID = 900000000) {
    $id_decode = hexdec($id) - $ID;
    return $id_decode;
}

function set_title($str) {
    return Yii::app()->name . ' - ' . $str;
}

function convert_time($date, $granularity = 1) {
    //$date = strtotime($date);
    $difference = time() - $date;
    if ($difference <= 1) {
        return '1 second ago';
    }
    $periods = array('decade' => 315360000,
        'year' => 31536000,
        'month' => 2628000,
        'week' => 604800,
        'day' => 86400,
        'hour' => 3600,
        'minute' => 60,
        'second' => 1);

    if ($difference > $periods['month']) {
        return date('F, d, Y', $date);
    } else {
        foreach ($periods as $key => $value) {
            if ($difference >= $value) {
                $time = floor($difference / $value);
                $difference %= $value;
                $retval .= ($retval ? ' ' : '') . $time . ' ';
                $retval .= (($time > 1) ? $key . 's' : $key);
                $granularity--;
            }
            if ($granularity == '0') {
                break;
            }
        }
        return $retval . ' ago';
    }
}

/**
 * Clear Tag html
 */
function check_html($str) {
    return strip_tags(trim($str));    
}

function short_text($var, $len) {
    if (strlen($var) < $len) {
        return $var;
    }
    $match = array();
    if (preg_match("/(.{1,$len})\s/ism", $var, $match)) {
        return $match [1] . "...";
    } else {
        return substr($var, 0, $len) . "...";
    }
}

function vietdecode($value) {
    $value = trim($value);
    $value = preg_replace("/(à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ)/", 'a', $value);
    $value = preg_replace("/(è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ)/", 'e', $value);
    $value = preg_replace("/(ì|í|ị|ỉ|ĩ)/", 'i', $value);
    $value = preg_replace("/(ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ)/", 'o', $value);
    $value = preg_replace("/(ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ)/", 'u', $value);
    $value = preg_replace("/(ỳ|ý|ỵ|ỷ|ỹ)/", 'y', $value);
    $value = preg_replace("/(đ)/", 'd', $value);
    $value = preg_replace("/(À|Á|Ạ|Ả|Ã|Â|Ầ|Ấ|Ậ|Ẩ|Ẫ|Ă|Ằ|Ắ|Ặ|Ẳ|Ẵ)/", 'A', $value);
    $value = preg_replace("/(È|É|Ẹ|Ẻ|Ẽ|Ê|Ề|Ế|Ệ|Ể|Ễ)/", 'E', $value);
    $value = preg_replace("/(Ì|Í|Ị|Ỉ|Ĩ)/", 'I', $value);
    $value = preg_replace("/(Ò|Ó|Ọ|Ỏ|Õ|Ô|Ồ|Ố|Ộ|Ổ|Ỗ|Ơ|Ờ|Ớ|Ợ|Ở|Ỡ)/", 'O', $value);
    $value = preg_replace("/(Ù|Ú|Ụ|Ủ|Ũ|Ư|Ừ|Ứ|Ự|Ử|Ữ)/", 'U', $value);
    $value = preg_replace("/(Ỳ|Ý|Ỵ|Ỷ|Ỹ)/", 'Y', $value);
    $value = preg_replace("/(Đ)/", 'D', $value);

    /**
     *   : = %3a   / = %2f   @ = %40
     *   + = %2b   ( = %28   ) = %29
     *   ? = %3f   = = %3d   & = %26 
     */
    $trans = array(
        ':' => '', '/' => '', '@' => '', '+' => '', '(' => '', ')' => '', '?' => '', '=' => '', '&' => ''
    );
    $value = strtr($value, $trans);

    $value = trim($value, '-');
    return strtolower($value);
}

/**
 * function clean URL
 * return string url chi co cac ky tu tu a-z, 0-9 va khong chap nhan cac ky tu dac biet
 */
function change_url_seo($string) {
    $value = vietdecode($string);
    $value = preg_replace("/[^a-zA-Z0-9\.]/ism", '-', $value);
    $value = preg_replace("/[\-]+/ism", '-', $value);
    preg_match_all('#[a-zA-Z0-9\s\-\+]+#im', $value, $matches);
    $value = implode('', $matches[0]);
    //bo di khoang gia
    $pattern = '/([0-9][0-9\.\,]+\-*[\/]*(d|vnd|bo)+\-*[\d\/]*)/ism';
    $value = preg_replace($pattern, '', $value);
    $value = trim($value);
    $value = preg_replace('/\s+/', '-', $value);
    $value = preg_replace('/(\+)+/', '-', $value);
    $value = preg_replace('/(\-)+/', '-', $value);
    return trim($value, '-');
}

/**
 * show du lieu dang htmlentities
 * VD: Hà " anh Mận => Hà " Anh Mận
 * @param type $str
 * @return type 
 */
function str2str($str) {
    return htmlentities($str, ENT_QUOTES | ENT_IGNORE, "UTF-8");
}

/**
 * send mail
 * @param string $from Email nguoi gui
 * @param string $to Email nguoi nhan
 * @param string $subject Tieu de mail
 * @param string $content Noi dung email (Chap nhan ca HTML)
 * @param string $fromName Ten nguoi gui (option)
 * @param int $server
 * - 1 
 *  $server = array('email' => 'no-reply@chonmua.com', 'password' => 'vb1234567');
 * - 2
 *  $server = array('email' => 'khuyenmai@chonmua.com', 'password' => 'vb12345678');
 * - 3
 *  $server = array('email' => 'banquantri@chonmua.com', 'password' => 'vb12345678');
 * @return boolean
 * @author ManPHP
 * @date 07-Oct-2011
 */
function send_mail($from = null, $to, $subject, $content, $cc = array(), $fromName = 'Jobs Search', $server = 1) {
    if (empty($to)) {
        return -1;
    }
    require_once ROOT_PATH . '/lib/phpmailer/class.phpmailer.php';
    if ($server == 1) {
        //$server = array('email' => 'manphp@binhhoang.com', 'password' => 'anhmantk');
        $server = array('email' => 'no-reply@chonmua.com', 'password' => 'vb1234567');
    } elseif ($server == 2) {
        $server = array('email' => 'khuyenmai@chonmua.com', 'password' => 'vb12345678');
    } elseif ($server == 3) {
        $server = array('email' => 'banquantri@chonmua.com', 'password' => 'vb12345678');
    }
    if ($from == null) {
        $from = $server['email'];
    }
    $mail = new PHPMailer();
    // set charset cho noi dung mail
    $mail->CharSet = "UTF8";
    // noi dung mail
    $body = $content;
    // khoi tao send mail voi SMTP
    // khoi tao send mail voi SMTP
    $mail->IsSMTP();
    $mail->SMTPAuth = true;                  // enable SMTP authentication
    $mail->SMTPSecure = "ssl";                 // sets the prefix to the servier
    $mail->Host = "smtp.googlemail.com";      // sets GMAIL as the SMTP server
    $mail->Port = 465;                   // set the SMTP port for the GMAIL server

    $mail->Username = $server['email'];  // GMAIL username
    $mail->Password = $server['password'];            // GMAIL password
    // add Reply khi an vao Reply
    $mail->AddReplyTo($from, $fromName);

    // Email nguoi gui
    $mail->From = $server['email'];
    // Ten nguoi gui
    $mail->FromName = $fromName;
    // Tieu de thu
    $mail->Subject = $subject;

    $mail->WordWrap = 50; // set word wrap
    // Noi dung mail co the de dang HTML
    $mail->MsgHTML($body);
    // email nguoi gui
    $mail->AddAddress($to);
    if (!empty($cc)) {
        foreach ($cc as $c) {
            $mail->AddCC($c);
        }
    }

    // Attachment
    //$mail->AddAttachment("images/phpmailer.gif");             // attachment
    // send as HTML
    $mail->IsHTML(true);

    if (!$mail->Send()) {
        //echo "Mailer Error: " . $mail->ErrorInfo;die;
        return false; // send error
    } else {
        return true; // send success
    }
}

/**
 * lay IP cua client
 * - hien server lom dung tam ham nay
 * - khi nao server hon thi dung ham cua drupal core: ip_address()
 * @staticvar string $ip_address
 * @return string
 */
function ip_address() {
    $ip_address = NULL;
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ip_address_parts = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        foreach ($ip_address_parts as $ip) {
            if ($ip != '127.0.0.1') {
                $ip_address = $ip;
                return $ip;
            }
        }
    } else {
        $ip_address = $_SERVER['REMOTE_ADDR'];
    }
    return $ip_address;
}

function drawCLinkPager($obj, $pages, $item_count, $page_size) {
    $obj->widget('CLinkPager', array(
        'firstPageCssClass' => 'first_page',
        'lastPageCssClass' => 'last_page',
        'previousPageCssClass' => 'first',
        'nextPageCssClass' => 'last',
        'currentPage' => $pages->getCurrentPage(),
        'itemCount' => $item_count,
        'pageSize' => $page_size,
        'maxButtonCount' => 5,
        'header' => '',
        'nextPageLabel' => 'Next',
        'prevPageLabel' => 'Previous',
        'htmlOptions' => array('class' => 'pagination'),
    ));
}

/**
 * @param type $msg
 * array | string
 * @param type $type 
 * errormsg | success | info | warning
 */
function createMessage($msg, $type = 'info') {
    Yii::app()->session['msg'] = $msg;
    Yii::app()->session['msg_type'] = $type;
}

function showMessage() {
    $html = '';
    $msg = Yii::app()->session['msg'];
    if (!empty($msg)) {
        $type = Yii::app()->session['msg_type'];
        $html .= '<div class="message ' . $type . '">';        
        if (is_array($msg)) {
            foreach ($msg as $m) {
                $html .= '<p>' . $m . '</p>';
            }
        } else {
            $html .= '<p>' . $msg . '</p>';
        }
        $html .= '</div>';
        unset(Yii::app()->session['msg']);
        unset(Yii::app()->session['msg_type']);
    }
    return $html;
}

function formatNumber($number, $delimiter = '.') {
    return number_format($number, 0, '', $delimiter);
}
/**
 * kiem tra dinh dang file anh truoc khi upload
 *
 * @param string $pattern        
 * @param string $filename        
 * @param string $tmp_file        
 * @return boolean @date 22/04/2012
 */
function image_match($filename, $tmp_file, $pattern = 'png|jpe?g|gif') {
    $pattern = '/^.*\.(' . $pattern . ')$/is';
    if (preg_match($pattern, $filename)) {
        if (getimagesize($tmp_file)) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}